package com.zzyl.service.impl;

import com.zzyl.mapper.ReservationMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
public class ReservationScheduleService {

    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 定时检查并更新过期预约状态
     * 每天凌晨1点执行一次
     */
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行
    @Transactional(rollbackFor = Exception.class)
    public void updateExpiredReservations() {
        try {
            log.info("开始执行过期预约状态更新任务...");
            
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            
            // 调用Mapper更新状态为0（待报道）且预约时间已过的记录
            int updatedCount = reservationMapper.updateReservationStatus(now);
            
            log.info("过期预约状态更新完成，共更新 {} 条记录", updatedCount);
            
        } catch (Exception e) {
            log.error("更新过期预约状态时发生错误", e);
            throw e; // 抛出异常让事务回滚
        }
    }

    /**
     * 更频繁的检查（可选）- 每30分钟检查一次
     */
    @Scheduled(cron = "0 */30 * * * ?") // 每30分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void updateExpiredReservationsFrequently() {
        try {
            log.debug("执行频繁过期预约检查...");
            
            LocalDateTime now = LocalDateTime.now();
            int updatedCount = reservationMapper.updateReservationStatus(now);
            
            if (updatedCount > 0) {
                log.info("频繁检查：更新了 {} 条过期预约记录", updatedCount);
            }
            
        } catch (Exception e) {
            log.error("频繁检查过期预约状态时发生错误", e);
            throw e;
        }
    }
}